package com.atguigu.spzx.pay.service.Impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.atguigu.spyx.model.common.Result;
import com.atguigu.spyx.model.common.ResultCodeEnum;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.h5.OrderItem;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.order.OrderInfo;
import com.atguigu.spyx.model.exception.SpzxException;
import com.atguigu.spzx.order.api.OrderClient;
import com.atguigu.spzx.pay.config.AlipayConfig;
import com.atguigu.spzx.pay.mapper.AplipayMapper;
import com.atguigu.spzx.pay.mapper.PaymentInfoMapper;
import com.atguigu.spzx.pay.service.AplipayService;
import com.atguigu.spzx.pay.service.PaymentInfoService;
import com.atguigu.spzx.product.api.ProductClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author LT
 * @create 2023-11-24-16:23
 */
@Slf4j
@Service
public class AplipayServiceImpl implements AplipayService {

    @Resource
    OrderClient orderClient;

    @Resource
    PaymentInfoService paymentInfoService;
    @Resource
    PaymentInfoMapper paymentInfoMapper;

    @Resource
    ProductClient productClient;


    @Override
    public String notifyUrl(Map<String, String> params) {
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
        } catch (AlipayApiException e){
            log.error("签名校验失败");
            return "fail";
        }
        if(verify_result){//验证成功
            String outTradeNo = params.get("out_trade_no");
            int count = paymentInfoMapper.countByTradeNo(outTradeNo);
            if(count>0){
                return "success";
            }
            Result<OrderInfo> result = orderClient.findOrderByOrderNo(Long.parseLong(outTradeNo));
            if (result.getCode()!=200){
                log.error("订单查询失败");
                return "fail";
            }
            OrderInfo orderInfo = result.getData();
            String buyPayAmount = params.get("buyer_pay_amount");
            if (orderInfo.getTotalAmount().compareTo(new BigDecimal(buyPayAmount))!=0){
                log.error("支付金额错误");
                return "fail";
            }
            String tradeStatus = params.get("trade_status");
            if(!"TRADE_SUCCESS".equals(tradeStatus)){
                //交易失败
                return "fail";
            }
            orderClient.updatePayStatus(Long.parseLong(orderInfo.getOrderNo()),2L,1L);

            List<OrderItem> orderItems = orderInfo.getOrderItemList();
            productClient.updateSalesAndStock(orderItems);
            paymentInfoService.save(orderInfo,params);
            return "success";
        }else{
            return "fail";
        }
    }

    @Override
    public String returnUrl(Map<String, String> params) {

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        boolean verify_result = false;
        try {
            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");
        } catch (AlipayApiException e){
            throw new SpzxException(ResultCodeEnum.ERROR,e);
        }
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        if(verify_result){//验证成功
            //给用户响应一个支付成功页面
            // 在spzx-h5 前端项目中准备一个成功页
            //跳转到 订单列表页
            return "redirect:http://www.spzx.com";
        }else{
            //验证失败
            //给用户响应支付失败页面
            // 在spzx-h5 前端项目中准备一个失败页
            return "redirect:http://www.spzx.com";
        }
    }

    @Override
    public String submitAlipay(Long orderNo) {

        String product_code="QUICK_WAP_WAY";
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(
                AlipayConfig.URL,
                AlipayConfig.APPID,
                AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(orderNo.toString());
        Result<OrderInfo> result = orderClient.findOrderByOrderNo(orderNo);
        if (result.getCode().intValue() !=200){
            throw new SpzxException(ResultCodeEnum.ERROR,null);
        }
        OrderInfo orderInfo = result.getData();
        String subject = StringUtils.join(orderInfo.getOrderItemList().stream().map(orderItem ->
                orderItem.getSkuName()).collect(Collectors.toList()), ",");
        model.setSubject(subject);

        model.setTotalAmount(orderInfo.getTotalAmount().toString());
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            System.out.println(form);
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new SpzxException(ResultCodeEnum.ERROR,e);
        }
        return form;
    }

}
